<!-- 区域块组件 -->
<template>
  <div class="electronSign">
    <div class="sign-box" @mouseenter="show = false" @mouseleave="show = true">
      <el-image v-if="imgSrc" :src="imgSrc" :style="'width:' + width + 'px;height:' + height + 'px;'" fit="fill"></el-image>
      <vue-esign v-else ref="esignRef" :width="width" :height="height" />
      <div v-show="show && !imgSrc" :style="'width:' + width + 'px;height:' + height + 'px;line-height: ' + height + 'px;'" class="tip">
        请在此处签名,签完后点击右侧保存
      </div>
    </div>
    <div v-if="update" class="btns">
      <el-button circle plain icon="Refresh" size="small" color="#FFB800" @click="resetSign"></el-button>
      <el-button circle plain icon="Check" size="small" color="#16b777" @click="getSignImg"></el-button>
    </div>
  </div>
</template>

<script setup>
  import vueEsign from 'vue-esign'
  import { uploadFileApi } from '@/api/api'
  import { ref, getCurrentInstance, watch, nextTick } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties

  // 定义父组件传入的值
  const props = defineProps({
    modelValue: String,
    width: {
      type: Number,
      default: 400,
      required: false
    },
    height: {
      type: Number,
      default: 200,
      required: false
    },
    update: {
      type: Boolean,
      default: true,
      required: false
    }
  })
  // 定义传值给父组件数据方法
  const emits = defineEmits(['update:modelValue'])

  const esignRef = ref(null)

  let imgSrc = ref('')
  let show = ref(true)
  
  watch(() => props.modelValue, (newVal) => {
    init()
  }, {
    immediate: true // 立即监听
  })

  function init() {
    imgSrc.value =  props.modelValue
  }
  init()

  // 获取签名图片，并上传签名图片
  function getSignImg() {
    esignRef.value.generate().then(res => {
      imgSrc.value = res
    }).catch(err => {
      currentThis.$message.error('请先签名')
    })
  }

  // 重置签名
  function resetSign() {
    imgSrc.value = ''
    nextTick(() => {
      esignRef.value.reset()
    })
  }
</script>

<style lang="less" scoped>
.electronSign{
  display: flex;
  .sign-box{
    position: relative;
    border-radius: 8px;
    border: #cccccc dashed 1px;
    .tip{
      position: absolute;
      top: 0;
      left: 0;
      text-align: center;
      font-size: 16px;
      color: #cccccc;
      z-index: 100;
      -webkit-user-select:none;
      -moz-user-select:none;
      -ms-user-select:none;
      user-select:none;
    }
  }
  .btns{
    display: flex;
    flex-direction: column;
    margin-left: 4px;
    .el-button+.el-button{
      margin: 6px 0 0 0;
    }
  }
}
</style>